<template>
  <div>
    <div class="con_top">
      <div v-for="item in dictKeyList" :key="item.dictKey" class="con_top_item">
        <pieCharts
          v-if="item.type === 'LINE'"
          :dictKey="item.dictKey"
          :data="item.data"
          :width="350"
          :height="360"
          :title="item.title"
          :rightText="rightText"
          :momFormat="momFormat"
          :yoyFormat="yoyFormat"
          :options="options"
          @topLeft="labelLayoutLeftFn(item)"
        />
        <barCharts
          v-if="item.type === 'BAR'"
          :dictKey="item.dictKey"
          :data="item.data"
          :width="716"
          :height="360"
          :title="item.title"
          :isWater="item.energyType === 'HOT_WATER'"
          :options="barOptions"
          :getSubKey="getSubKey.fn"
          @topRight="labelLayoutRightFn(item, subIndicatorItem)"
        />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import pieCharts from "@/views/common/energy/components/pieCharts/index.vue";
import barCharts from "@/views/common/energy/components/barCharts/index.vue";
import { totalConsumption, barChart } from "@/api/modules/energy";
import { subSystemIndicator } from "@/api/modules/energy";
import { reactive, ref } from "vue";

interface Props {
  /**  有 title 时传入 */
  energyTitle?: string;
  title?: string;
  /**  有按钮时传入，传入后会有 btn-click 事件 */
  button?: string;
  activeName?: string;
  /**  title 栏右侧文字 */
  // rightText?: string | number;
  /**  模块最低宽度，默认 330px */
  width?: number;
  /**  模块最低高度，默认 200px */
  height?: number;
  /**  是否需要背景阴影，默认为true */
  boxShadow?: boolean;
  /**  是否需要圆角，默认为true */
  borderRidus?: boolean;
  /**是否搜索 */
  isSerch?: boolean;
  /**科室 */
  className?: any;
  /**能源类型 */
  energyType?: string;
  queryTimeType?: string;
  queryParams?: any;
  dateRange?: any;
  dictKeyList: Array<any>;
}

const options = ref<CommonEcharts.CommonEchartsOption>(null);
const barOptions = ref<CommonEcharts.CommonEchartsOption>(null);

type itemStyleType = {
  [key: string]: string;
};

interface dataType {
  name: string;
  value: number;
  itemStyle?: itemStyleType;
}

const props = withDefaults(defineProps<Props>(), {});
const subIndicatorItem = ref<any>({});

const getSubKey = reactive({
  fn: (val: any) => {
    subIndicatorItem.value = val;
  }
});

const dataList = ref([
  {
    name: "能耗费用",
    valueFormat: "123,45",
    unit: "万元",
    percent: "12",
    icon: "elec_money"
  },
  {
    name: "累计用电量",
    valueFormat: "112,35",
    unit: "tCO2e",
    percent: "12",
    icon: "elec_used"
  },
  {
    name: "累计折标煤",
    valueFormat: "221,42",
    unit: "tCO2e",
    percent: "12",
    icon: "elec_mei"
  },
  {
    name: "累计用电量",
    valueFormat: "112,35",
    unit: "tCO2e",
    percent: "12",
    icon: "elec_used"
  },
  {
    name: "累计折标煤",
    valueFormat: "221,42",
    unit: "tCO2e",
    percent: "12",
    icon: "elec_mei"
  },
  {
    name: "累计用电量",
    valueFormat: "112,35",
    unit: "tCO2e",
    percent: "12",
    icon: "elec_used"
  },
  {
    name: "累计折标煤",
    valueFormat: "221,42",
    unit: "tCO2e",
    percent: "12",
    icon: "elec_mei"
  },
  {
    name: "累计碳排放",
    valueFormat: "123,12",
    unit: "tCO2e",
    percent: "12",
    icon: "elec_co2"
  }
]);
const rightText = ref<string | number>();

// 能源-HOT_WATER饼图
const labelLayoutFnWater = (ec: any, dataInner: Array<dataType>, dataOuter: Array<dataType>, title: string, unit: string) => {
  const { getWidth } = ec;
  const labelLayout = function (params) {
    const isLeft = params.labelRect.x < getWidth() / 2;
    const points = params.labelLinePoints;
    points[2][0] = isLeft ? params.labelRect.x : params.labelRect.x + params.labelRect.width;
    return { labelLinePoints: points };
  };
  const options: CommonEcharts.CommonEchartsOption = {
    tooltip: {
      trigger: "item",
      formatter: `{a} <br/>{b}: {c}${unit} ({d}%)`
    },
    series: [
      {
        name: title,
        type: "pie",
        selectedMode: "single",
        radius: [0, "40%"],
        color: ["#00E272", "#3B82F6"],
        label: {
          color: "#000",
          position: "inner",
          formatter: "{b}\n{d}%",
          fontSize: 14,
          fontWeight: "bold"
        },
        labelLine: {
          show: false
        },
        data: dataInner
      },
      {
        name: title,
        type: "pie",
        radius: ["55%", "70%"],
        labelLine: {
          length: 30
        },
        label: {
          formatter: `{b}{per|{d}%}\n{c|{c}${unit}}`,
          rich: {
            a: {
              color: "#6E7079",
              lineHeight: 22,
              align: "center"
            },
            b: {
              color: "#4C5058",
              fontSize: 14,
              fontWeight: "bold",
              lineHeight: 33
            },
            c: {
              fontSize: 14,
              fontWeight: "bold"
            }
          }
        },
        data: dataOuter
      }
    ]
  };
  return options;
};

// 能源- 其他类型 饼图
const labelLayoutFn = (ec: any, dataInner: Array<dataType>, dataOuter: Array<dataType>, title: string, unit: string) => {
  const { getWidth } = ec;
  const labelLayout = function (params) {
    const isLeft = params.labelRect.x < getWidth() / 2;
    const points = params.labelLinePoints;
    points[2][0] = isLeft ? params.labelRect.x : params.labelRect.x + params.labelRect.width;
    return { labelLinePoints: points };
  };
  const options: CommonEcharts.CommonEchartsOption = {
    tooltip: {
      trigger: "item",
      formatter: `{b}: {c}${unit} ({d}%)`,
      textStyle: {
        fontSize: 12
      }
    },
    // legend: {
    //   data: ["Direct", "Marketing", "Search Engine", "Email", "Union Ads", "Video Ads", "Baidu", "Google", "Bing", "Others"]
    // },
    series: [
      {
        name: title,
        type: "pie",
        selectedMode: "single",
        radius: [0, "45%"],
        label: {
          color: "#000",
          position: "inner",
          formatter: "{b}\n{d}%",
          fontSize: 12,
          fontWeight: "bold"
        },
        labelLine: {
          show: false
        },
        itemStyle: {
          borderWidth: 2,
          borderColor: "#fff"
        },
        data: dataInner
      },
      {
        name: title,
        type: "pie",
        radius: ["45%", "60%"],
        labelLine: {
          length: 30
        },
        label: {
          formatter: `{b|{b}} {per|{d}%}\n {c|{c}}{x|${unit}}  `,
          borderWidth: 1,
          borderRadius: 4,
          rich: {
            hr: {
              borderColor: "#8C8D8E",
              width: "100%",
              borderWidth: 1,
              height: 0
            },
            b: {
              color: "#4C5058",
              fontSize: 12,
              lineHeight: 15
            },
            per: {
              color: "#4C5058",
              padding: [3, 4],
              borderRadius: 4,
              fontSize: 12
            },
            c: {
              color: "#4C5058",
              fontSize: 12
            },
            x: {
              color: "#4C5058",
              fontSize: 12
            }
          }
        },
        itemStyle: {
          borderWidth: 2,
          borderColor: "#fff"
        },
        data: dataOuter
      }
    ]
  };
  return options;
};

// 柱状图
const labelLayoutFnBar = (ec: any, xdata: string[], data: number[], title: string, unit: string) => {
  const { getWidth } = ec;
  // labelLine长度
  const labelLayout = function (params) {
    const isLeft = params.labelRect.x < getWidth() / 2;
    const points = params.labelLinePoints;
    points[2][0] = isLeft ? params.labelRect.x : params.labelRect.x + params.labelRect.width;
    return { labelLinePoints: points };
  };
  const options: CommonEcharts.CommonEchartsOption = {
    tooltip: {
      trigger: "axis",
      formatter: `{b}: {c}${unit}`
    },
    // calculable: true,
    xAxis: [
      {
        type: "category",
        // prettier-ignore
        data: xdata
      }
    ],
    yAxis: [
      {
        type: "value",
        name: `${unit}`,
        nameTextStyle: {
          color: "#aaa"
        }
      }
    ],
    series: [
      {
        name: "Rainfall",
        type: "bar",
        data,
        itemStyle: {
          color: "#3B82F6"
        },
        markPoint: {
          data: [
            { type: "max", name: "Max" },
            { type: "min", name: "Min" }
          ],
          // 修改标记点的样式
          itemStyle: {
            color: "#FFBC68" // 标记点的颜色
          },
          label: {
            show: true, // 显示标签
            formatter: `{c}${unit}`, // 标签格式
            color: "black" // 标签颜色
          }
        },
        markLine: {
          data: [{ type: "average", name: "Avg" }],
          label: {
            show: true, // 显示标签
            position: "middle", // 标签位置
            formatter: `平均值：{c}${unit}`, // 标签格式
            color: "#3B82F6" // 标签颜色
          }
        }
      }
    ]
  };
  return options;
};

const getParams = (val: any) => {
  return {
    ...props.queryParams,
    startTime: props.dateRange && props.dateRange.length ? props.dateRange[0] : props.queryParams.startTime,
    endTime: props.dateRange && props.dateRange.length ? props.dateRange[1] : props.queryParams.endTime,
    energyType: props.energyType,
    className: props.className,
    queryTimeType: props.queryTimeType,
    dictKey: val.dictKey
  };
};

const momFormat = ref(""); // 环比
const yoyFormat = ref(""); // 同比

// 获取能耗数据
const labelLayoutLeftFn = async (ec: any) => {
  const title = ec.title;
  const unit = ec.unit;
  const isWater = ec.energyType === "HOT_WATER";
  const params = getParams(ec);
  const res: any = await totalConsumption(isWater, { dictKey: ec.dictKey, ...params });
  rightText.value = res?.totalWaterConsumption !== null && res?.totalWaterConsumption !== undefined ? res?.totalWaterConsumption + ec.unit : "";
  momFormat.value = res?.momFormat;
  yoyFormat.value = res?.yoyFormat;
  if (isWater) {
    if (!res?.inner.length && !res?.outer.length) return null;
    const dataInner = res?.inner;
    const dataOuter = res?.outer;
    options.value = labelLayoutFnWater(ec, dataInner, dataOuter, title, unit);
  } else {
    if (!res?.details.length) return null;
    const colorList = ["#00E272", "#2FE0AC", "#FE6A35"];
    const itemColorList = ["#30ffa0", "#60fffc", "#ff9e68"];
    let detailList = [];
    let itemList = [];
    const length = res?.details.length;
    for (let i = 0; i < length; i++) {
      const { name, value } = res?.details[i];
      detailList.push({ name, value, itemStyle: { color: colorList[i] } });
      res?.details[i]?.childDetails.map((el: any) => {
        const { name, value } = el;
        itemList.push({ name, value, itemStyle: { color: itemColorList[i] } });
      });
    }
    const dataInner = detailList;
    const dataOuter = itemList;
    options.value = labelLayoutFn(ec, dataInner, dataOuter, title, unit);
  }
};

// 获取子系统指标
const getIndicatorKey = async (ec: any) => {
  if (ec.energyType !== "HOT_WATER") {
    return null;
  }
  const res: any = await subSystemIndicator({
    dictKey: ec.dictKey
  });
  if (res.subSystemIndicator && res.subSystemIndicator.length) {
    const item = res.subSystemIndicator.filter((item: any) => item.name === "总水")[0];
    subIndicatorItem.value = item;
  }
  return subIndicatorItem.value || null;
};

// 柱状图
const labelLayoutRightFn = async (ec: any, item: any) => {
  const title = ec.title;
  const unit = ec.unit;
  const params = getParams(ec);
  const isWater = ec.energyType === "HOT_WATER";
  const obj: any = Object.keys(item).length !== 0 ? item : await getIndicatorKey(ec);
  const res: any = await barChart(isWater, { ...params, ...obj });
  if (!res?.detail || !res?.detail.length) return null;
  const xData = getValueList(res?.detail, "timeFormat");
  const seriesData = getValueList(res?.detail, "value");
  barOptions.value = labelLayoutFnBar(ec, xData, seriesData, title, unit);
};

// 获取对象数组某一项value组成的数组
const getValueList = (arr: any[], key: number | string) => {
  let valueList = [];
  arr.forEach(item => {
    valueList.push(item[key]);
  });
  return valueList;
};
</script>

<style scoped lang="scss">
.con_top {
  display: flex;
  justify-content: space-between;
  width: 100%;
  min-width: 1300px;
  height: 360px;
  margin-bottom: 16px;

  .con_top_item:nth-child(1) {
    width: 100%;
  }
}
</style>
